package com.dailyblue.java.project.bookstore.book.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dailyblue.java.project.bookstore.book.bean.Book;
import com.dailyblue.java.project.bookstore.book.feign.AuthorService;
import com.dailyblue.java.project.bookstore.book.feign.CountService;
import com.dailyblue.java.project.bookstore.book.feign.PubInfoService;
import com.dailyblue.java.project.bookstore.book.mapper.BookMapper;
import com.dailyblue.java.project.bookstore.book.service.BookService;
import com.dailyblue.java.project.bookstore.book.util.JsonResult;
import com.dailyblue.java.project.bookstore.book.util.ResultTool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
@Slf4j
public class BookServiceImpl extends ServiceImpl<BookMapper, Book> implements BookService {
    @Resource
    private BookMapper bookMapper;
    @Resource
    private AuthorService authorService;
    @Resource
    private PubInfoService pubInfoService;
    @Resource
    private CountService countService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Cacheable(cacheNames = "findBookByNewArrival", key = "0")
    public JsonResult findBookByNewArrival() {
        log.info("开始检索最新上架图书");
        List<Book> list = bookMapper.findBookByNewArrival();
        for (Book book : list) {
            int authorId = book.getAuthorId();
            int pubId = book.getPubId();
            JsonResult author = authorService.findAuthorById(authorId);
            JsonResult pub = pubInfoService.findPubInfoById(pubId);
            log.info("获取到了id:{}的作者信息：{}", authorId, author);
            log.info("获取到了id:{}的出版社信息：{}", pubId, pub);
            book.setAuthor(author);
            book.setPubInfo(pub);
        }
        return ResultTool.success(list);
    }

    //@Cacheable(cacheNames = "findBookById",key = "#id")
    public JsonResult findBookById(int id) {
        ValueOperations value = stringRedisTemplate.opsForValue();
        // 去掉用统计微服务给当前图书点击率+1
        JsonResult count = countService.book(id);
        Book book = getById(id);
        int authorId = book.getAuthorId();
        int pubId = book.getPubId();
        JsonResult author = authorService.findAuthorById(authorId);
        JsonResult pub = pubInfoService.findPubInfoById(pubId);
        book.setPubInfo(pub);
        book.setAuthor(author);
        book.setCount(count);
        JsonResult result = ResultTool.success(book);
        result.setMessage(book.getBookPrice() + "");
        value.set("findBookById::" + id, JSONArray.toJSONString(result));
        return result;
    }


}
